package com.ihr360.job.core.item.support;

import com.ihr360.job.core.item.ItemWriter;
import org.springframework.data.util.Pair;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapMapItemWriter<K, T extends Map> implements ItemWriter<Pair> {

    private Map<K, Map> writtenItems = new HashMap<>();

    @Override
    public void write(List<? extends Pair> pairs) throws Exception {
        for (Pair<K, ? extends Map> pair : pairs) {
            K first = pair.getFirst();
            Map second = pair.getSecond();
            if (writtenItems.containsKey(first)) {
                Map item = writtenItems.get(first);
                for (Object key : second.keySet()) {
                    item.put(key, second.get(key));
                }
            } else {
                writtenItems.put(pair.getFirst(), second);
            }
        }
    }

    public Map<K, Map> getWrittenItems() {
        return this.writtenItems;
    }
}
